package vn.edu.tdt.it.domain;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import javax.xml.stream.events.EndElement;
import javax.xml.stream.events.StartElement;

import vn.edu.tdt.it.common.OWLConst;

public class Dictionary {
	
	public static void main(String[] args) throws Exception {
		StaticConnection.DB_URL = "jdbc:mysql://localhost/wiki?useUnicode=true&characterEncoding=UTF-8";
		OWLConst.FILE_NAME = "Dictionary.owl";
		OWLBuilder.init();
		StartElement configStartElement = OWLBuilder.eventFactory.createStartElement("",
				"", OWLConst.TAG_BEGIN);
		OWLBuilder.eventWriter.add(OWLBuilder.end);
		OWLBuilder.eventWriter.add(configStartElement);
		OWLBuilder.eventWriter.add(OWLBuilder.end);
		
		String sql = "SELECT DISTINCT pageId FROM pagemapline";
		ResultSet rs = StaticConnection.getStatement().executeQuery(sql);
		while (rs.next()) {
			sql = "SELECT id, name, pageId FROM pagemapline WHERE pageId = ? ORDER BY id ASC";
			PreparedStatement ps = StaticConnection.getPreparedStatement(sql);
			ps.setInt(1, rs.getInt(1));
			ResultSet rs2 = ps.executeQuery();
			String pname = "";
			List<String> child = new ArrayList<String>();
			while (rs2.next()) {
				int id = rs2.getInt(1);
				String name = rs2.getString(2);
				int pid = rs2.getInt(3);
				if (id == pid) {
					System.out.println("Processing parent: " + name);
					pname = name;
					OWLBuilder.createDictionaryNode(name, null);
				} else {
					child.add(name);
				}
			}
			for (String n: child) {
				System.out.println("Processing child: " + n);
				OWLBuilder.createDictionaryNode(n, pname);
			}
		}
		EndElement configEndElement = OWLBuilder.eventFactory.createEndElement("", "",
				"rdf:RDF");
		OWLBuilder.eventWriter.add(configEndElement);
		OWLBuilder.eventWriter.close();
	}
}
